package com.dyna.utils;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSON;
import com.dyna.constants.RedisKeyConstant;
import com.dyna.constants.StringPool;
import com.dyna.core.exception.CustomException;
import com.dyna.core.utils.JsonUtil;
import com.dyna.core.utils.ObjectUtil;
import com.dyna.entity.DelayMessage;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.springframework.dao.InvalidDataAccessApiUsageException;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.geo.Point;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.*;
import org.springframework.data.redis.core.ZSetOperations.TypedTuple;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author Admin
 */
@Slf4j
public class RdsUtil {

    public static StringRedisTemplate stringRedisTemplate;
    private static RedissonClient redissonClient;

    static {
        RdsUtil.stringRedisTemplate = SpringUtil.getBean(StringRedisTemplate.class);
        RdsUtil.redissonClient = SpringUtil.getBean(RedissonClient.class);
    }

    private static final String LUA_INCR_EXPIRE =
            "local key,ttl=KEYS[1],ARGV[1] \n" +
                    " \n" +
                    "if redis.call('EXISTS',key)==0 then   \n" +
                    "  redis.call('SETEX',key,ttl,1) \n" +
                    "  return 1 \n" +
                    "else \n" +
                    "  return tonumber(redis.call('INCR',key)) \n" +
                    "end ";

    public static Long inc(String key, int time, TimeUnit unit) {
        RedisScript<Long> redisScript = new DefaultRedisScript<>(LUA_INCR_EXPIRE, Long.class);
        return stringRedisTemplate.execute(redisScript, Collections.singletonList(key), String.valueOf(unit.toSeconds(time)));
    }

    /**
     * 指定缓存失效时间
     *
     * @param key  键
     * @param time 时间(秒)
     */
    public static Boolean expire(String key, long time) {
        try {
            if (time > 0) {
                stringRedisTemplate.expire(key, time, TimeUnit.SECONDS);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return false;
        }
        return true;
    }

    /**
     * 指定缓存失效时间
     *
     * @param key      键
     * @param time     时间(秒)
     * @param timeUnit 单位
     */
    public static Boolean expire(String key, long time, TimeUnit timeUnit) {
        try {
            if (time > 0) {
                stringRedisTemplate.expire(key, time, timeUnit);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return false;
        }
        return true;
    }

    /**
     * 根据 key 获取过期时间
     *
     * @param key 键 不能为null
     * @return 时间(秒) 返回0 代表为永久有效
     */
    public static Long getExpire(String key) {
        return stringRedisTemplate.getExpire(key, TimeUnit.SECONDS);
    }

    /**
     * 根据 key 获取过期时间
     *
     * @param key 键 不能为null
     * @return 时间(秒) 返回0 代表为永久有效
     */
    public static Long getExpire(String key, TimeUnit timeUnit) {
        return stringRedisTemplate.getExpire(key, timeUnit);
    }

    /**
     * 查找匹配key
     *
     * @param pattern key
     * @return /
     */
    public static List<String> scan(String pattern) {
        ScanOptions options = ScanOptions.scanOptions().match(pattern).build();
        RedisConnectionFactory factory = stringRedisTemplate.getConnectionFactory();
        RedisConnection rc = Objects.requireNonNull(factory).getConnection();
        Cursor<byte[]> cursor = rc.scan(options);
        List<String> result = new ArrayList<>();
        while (cursor.hasNext()) {
            result.add(new String(cursor.next()));
        }
        try {
            RedisConnectionUtils.releaseConnection(rc, factory);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 分页查询 key
     *
     * @param patternKey key
     * @param page       页码
     * @param size       每页数目
     * @return /
     */
    public static List<String> findKeysForPage(String patternKey, int page, int size) {
        ScanOptions options = ScanOptions.scanOptions().match(patternKey).build();
        RedisConnectionFactory factory = stringRedisTemplate.getConnectionFactory();
        RedisConnection rc = Objects.requireNonNull(factory).getConnection();
        Cursor<byte[]> cursor = rc.scan(options);
        List<String> result = new ArrayList<>(size);
        int tmpIndex = 0;
        int fromIndex = page * size;
        int toIndex = page * size + size;
        while (cursor.hasNext()) {
            if (tmpIndex >= fromIndex && tmpIndex < toIndex) {
                result.add(new String(cursor.next()));
                tmpIndex++;
                continue;
            }
            // 获取到满足条件的数据后,就可以退出了
            if (tmpIndex >= toIndex) {
                break;
            }
            tmpIndex++;
            cursor.next();
        }
        try {
            RedisConnectionUtils.releaseConnection(rc, factory);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 判断key是否存在
     *
     * @param key 键
     * @return true 存在 false不存在
     */
    public static Boolean hasKey(String key) {
        try {
            return stringRedisTemplate.hasKey(key);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return false;
        }
    }


    /**
     * 删除缓存
     * @param keys 删除的key
     */
    public static void del(String... keys) {
        if (keys != null && keys.length > 0) {
            if (keys.length == 1) {
                Boolean result = stringRedisTemplate.delete(keys[0]);
                log.debug("--------------------------------------------");
                log.debug("删除缓存：" + keys[0] + "，结果：" + result);
            } else {
                Set<String> keySet = new HashSet<>();
                for (String key : keys) {
                    Set<String> stringSet = stringRedisTemplate.keys(key);
                    if (Objects.nonNull(stringSet) && !stringSet.isEmpty()) {
                        keySet.addAll(stringSet);
                    }
                }
                Long count = stringRedisTemplate.delete(keySet);
                log.debug("--------------------------------------------");
                log.debug("成功删除缓存：" + keySet);
                log.debug("缓存删除数量：" + count + "个");
            }
            log.debug("--------------------------------------------");
        }
    }

    public static void del(List<String> keys) {
        stringRedisTemplate.delete(keys);
    }

    /**
     * Object转String
     * @return String
     */
    public static String objToStr(Object value) {
        String strValue;
        if (value instanceof String) {
            strValue = (String) value;
        }else if (ObjectUtil.isNull(value)) {
            strValue = StringPool.EMPTY;
        }else {
            strValue = JSON.toJSONString(value);
        }
        return strValue;
    }

    /**
     * redis自增
     * @param key key
     * @return 值
     */
    public static Integer incr(String key) {
        return Objects.requireNonNull(opsForValue().increment(key)).intValue();
    }
    public static Integer incr(String key, Long delta) {
        return Objects.requireNonNull(opsForValue().increment(key,delta)).intValue();
    }

    /**
     * redis自减
     * @param key key
     * @return 值
     */
    public static Integer decrement(String key) {
        return decrement(key,1L);
    }
    public static Integer decrement(String key, Long delta) {
        return Objects.requireNonNull(opsForValue().decrement(key, delta)).intValue();
    }

    /*============================String=============================*/

    public static ValueOperations<String, String> opsForValue() {
        return stringRedisTemplate.opsForValue();
    }

    /**
     * 普通缓存放入
     *
     * @param key   键
     * @param value 值
     * @return true成功 false失败
     */
    public static Boolean set(String key, String value) {
        value = ObjectUtil.isNull(value)? StringPool.EMPTY:value;
        try {
            log.debug("--------------------------------------------");
            stringRedisTemplate.opsForValue().set(key, value);
            log.debug("Redis键值对存储 ==> key: {}, value: {}", key, value);
            log.debug("--------------------------------------------");
            return true;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return false;
        }
    }

    /**
     * 普通缓存放入并设置时间
     *
     * @param key   键
     * @param value 值
     * @param time  时间(秒) time要大于0 如果time小于等于0 将设置无限期
     * @return true成功 false 失败
     */
    public static Boolean set(String key, String value, long time) {
        value = ObjectUtil.isNull(value)? StringPool.EMPTY:value;
        try {
            if (time > 0) {
                log.debug("--------------------------------------------");
                stringRedisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
                log.debug("Redis键值对存储 ==> key: {}, value: {}, expire: {}, unit:{}", key, value, time, TimeUnit.SECONDS);
                log.debug("--------------------------------------------");
            } else {
                set(key, value);
            }
            return true;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return false;
        }
    }

    /**
     * 普通缓存放入并设置时间
     *
     * @param key      键
     * @param value    值
     * @param time     时间
     * @param timeUnit 类型
     * @return true成功 false 失败
     */
    public static Boolean set(String key, String value, long time, TimeUnit timeUnit) {
        value = ObjectUtil.isNull(value)? StringPool.EMPTY:value;
        try {
            if (time > 0) {
                log.debug("--------------------------------------------");
                stringRedisTemplate.opsForValue().set(key, value, time, timeUnit);
                log.debug("Redis键值对存储 ==> key: {}, value: {}, expire: {}, unit:{}", key, value, time, timeUnit);
                log.debug("--------------------------------------------");
            } else {
                set(key, value);
            }
            return true;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return false;
        }
    }

    /**
     * 普通缓存获取
     *
     * @param key 键
     * @return 值
     */
    public static String get(String key) {
        return key == null ? null : stringRedisTemplate.opsForValue().get(key);
    }

    public static <T> T get(String key, Class<T> tClass) {
        String s = get(key);
        return toBeanOrNull(s, tClass);
    }

    /**
     * 批量set
     * @param map map
     * @param time 时间
     */
    public static <T> void mSet(Map<String, String> map, long time) {
        stringRedisTemplate.opsForValue().multiSet(map);
        map.forEach((key, value) -> {
            expire(key, time);
        });
    }

    public static <T> List<T> mGet(Collection<String> keys, Class<T> tClass) {
        List<String> list = stringRedisTemplate.opsForValue().multiGet(keys);
        assert list != null;
        list = list.stream().filter(ObjUtil::isNotNull).collect(Collectors.toList());
        if (CollUtil.isEmpty(list)) {
            return new ArrayList<>();
        }
        return list.stream().map(o -> toBeanOrNull(o, tClass)).collect(Collectors.toList());
    }

    static <T> T toBeanOrNull(String json, Class<T> tClass) {
        return json == null ? null : JsonUtil.toObj(json, tClass);
    }

    /*================================Map=================================*/
    /**
     * 向一张hash表中放入数据,如果不存在将创建
     *
     * @param key   键
     * @param item  项
     * @param value 值
     * @return true 成功 false失败
     */
    public static Boolean hSet(String key, String item, Object value) {
        try {
            stringRedisTemplate.opsForHash().put(key, item, objToStr(value));
            return true;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return false;
        }
    }

    /**
     * 向一张hash表中放入数据,如果不存在将创建
     *
     * @param key   键
     * @param item  项
     * @param value 值
     * @param time  时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间
     * @return true 成功 false失败
     */
    public static Boolean hSet(String key, String item, Object value, long time) {
        try {
            stringRedisTemplate.opsForHash().put(key, item, objToStr(value));
            if (time > 0) {
                expire(key, time);
            }
            return true;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return false;
        }
    }

    /**
     * HashSet
     *
     * @param key 键
     * @param map 对应多个键值
     * @return true 成功 false 失败
     */
    public static Boolean hmSet(String key, Map<String, Object> map) {
        Map<String, String> strMap = new HashMap<>();
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            strMap.put(entry.getKey(), objToStr(entry.getValue()));
        }

        try {
            log.debug("--------------------------------------------");
            stringRedisTemplate.opsForHash().putAll(key, strMap);
            log.debug("Redis键值对存储 ==> key: {}, value: {}", key, strMap);
            log.debug("--------------------------------------------");
            return true;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return false;
        }
    }

    /**
     * HashSet 并设置时间
     *
     * @param key  键
     * @param map  对应多个键值
     * @param time 时间(秒)
     * @return true成功 false失败
     */
    public static Boolean hmSet(String key, Map<String, Object> map, long time) {
        try {
            stringRedisTemplate.opsForHash().putAll(key, map);
            if (time > 0) {
                expire(key, time);
            }
            return true;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return false;
        }
    }

    /**
     * HashGet
     *
     * @param key  键 不能为null
     * @param item 项 不能为null
     * @return 值
     */
    public static Object hGetItem(String key, String item) {
        return stringRedisTemplate.opsForHash().get(key, item);
    }

    /**
     * 获取hashKey对应的所有键值
     *
     * @param key 键
     * @return 对应的多个键值
     */
    public static Map<Object, Object> hmGet(String key) {
        return stringRedisTemplate.opsForHash().entries(key);

    }

    /**
     * 删除hash表中的值
     *
     * @param key  键 不能为null
     * @param item 项 可以使多个 不能为null
     */
    public static void hDel(String key, Object... item) {
        stringRedisTemplate.opsForHash().delete(key, item);
    }

    /**
     * 判断hash表中是否有该项的值
     *
     * @param key  键 不能为null
     * @param item 项 不能为null
     * @return true 存在 false不存在
     */
    public static Boolean hHasKey(String key, String item) {
        return stringRedisTemplate.opsForHash().hasKey(key, item);
    }

    /**
     * hash递增 如果不存在,就会创建一个 并把新增后的值返回
     *
     * @param key  键
     * @param item 项
     * @param by   要增加几(大于0)
     * @return Double
     */
    public static Double hIncr(String key, String item, double by) {
        return stringRedisTemplate.opsForHash().increment(key, item, by);
    }

    /**
     * hash递减
     *
     * @param key  键
     * @param item 项
     * @param by   要减少记(小于0)
     * @return Double
     */
    public static Double hDecr(String key, String item, double by) {
        return stringRedisTemplate.opsForHash().increment(key, item, -by);
    }

    /*============================set=============================*/

    /**
     * 将数据放入set缓存
     *
     * @param key    键
     * @param values 值 可以是多个
     * @return 成功个数
     */
    public static Long  sSet(String key, Object... values) {
        try {
            String[] s = new String[values.length];
            for (int i = 0; i < values.length; i++) {
                if (null == values[i]) {
                    continue;
                }
                s[i] = objToStr(values[i]);
            }
            return stringRedisTemplate.opsForSet().add(key, s);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return 0L;
        }
    }

    /**
     * 根据key获取Set中的所有值
     *
     * @param key 键
     * @return Set<String>
     */
    public static Set<String> sGet(String key) {
        try {
            return stringRedisTemplate.opsForSet().members(key);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return null;
        }
    }

    /**
     * 根据value从一个set中查询,是否存在
     *
     * @param key   键
     * @param value 值
     * @return true 存在 false不存在
     */
    public static Boolean sHasKey(String key, String value) {
        if (ObjectUtil.isNull(value)) {
            throw new CustomException("查询value不能为空");
        }
        try {
            return stringRedisTemplate.opsForSet().isMember(key, value);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return false;
        }
    }

    /**
     * 将set数据放入缓存
     *
     * @param key    键
     * @param time   时间(秒)
     * @param values 值 可以是多个
     * @return 成功个数
     */
    public static Long sSetAndTime(String key, long time, Object... values) {
        try {
            String[] s = new String[values.length];
            for (int i = 0; i < values.length; i++) {
                s[i] = objToStr(values[i]);
            }
            Long count = stringRedisTemplate.opsForSet().add(key, s);
            if (time > 0) {
                expire(key, time);
            }
            return count;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return 0L;
        }
    }

    /**
     * 获取set缓存的长度
     *
     * @param key 键
     * @return Long
     */
    public static Long sSetSize(String key) {
        try {
            return stringRedisTemplate.opsForSet().size(key);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return 0L;
        }
    }

    /**
     * 移除值为value的
     *
     * @param key    键
     * @param values 值 可以是多个
     * @return 移除的个数
     */
    public static Long setRemove(String key, Object... values) {
        try {
            return stringRedisTemplate.opsForSet().remove(key, values);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return 0L;
        }
    }

    /*===============================list=================================*/

    /**
     * 将list放入缓存
     *
     * @param key   键
     * @param value 值
     * @return Boolean
     */
    public static Boolean lRightPushList(String key, Object value) {
        return lRightPushList(key, value, 0, TimeUnit.SECONDS);
    }

    /**
     * 将list放入缓存
     *
     * @param key   键
     * @param value 值
     * @return Boolean
     */
    public static Boolean lRightPushList(String key, Object value, long time, TimeUnit timeUnit) {
        if (cn.hutool.core.util.ObjectUtil.isNull(value)) {
            return Boolean.FALSE;
        }
        try {
            log.debug("--------------------------------------------");
            stringRedisTemplate.opsForList().rightPush(key, objToStr(value));
            log.debug("Redis List right push  ==> key: {}, value: {}", key, value);
            log.debug("--------------------------------------------");
            if (time > 0) {
                expire(key, time, timeUnit);
            }
            return true;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return false;
        }
    }

    /**
     * 将list放入缓存
     *
     * @param key 键
     * @param value 值
     * @return Boolean
     */
    public static Boolean lBatchRightPushList(String key, List<?> value) {
        return lBatchRightPushList(key, value, 0, TimeUnit.SECONDS);
    }

    /**
     * 将list放入缓存
     *
     * @param key   键
     * @param value 值
     * @param time  时间(秒)
     * @return Boolean
     */
    public static Boolean lBatchRightPushList(String key, List<?> value, long time, TimeUnit timeUnit) {
        try {
            List<String> stringList = value.stream().filter(cn.hutool.core.util.ObjectUtil::isNotNull).map(RdsUtil::objToStr).collect(Collectors.toList());
            log.debug("--------------------------------------------");
            stringRedisTemplate.opsForList().rightPushAll(key, stringList);
            log.debug("Redis List batch right push  ==> key: {}, value: {}", key, stringList);
            log.debug("--------------------------------------------");

            if (time > 0) {
                expire(key, time, timeUnit);
            }
            return true;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return false;
        }
    }

    /**
     * 将list放入缓存
     *
     * @param key   键
     * @param value 值
     * @return Boolean
     */
    public static Boolean lLeftPushList(String key, Object value) {
        return lLeftPushList(key, value, 0, TimeUnit.SECONDS);
    }

    /**
     * 将list放入缓存
     *
     * @param key   键
     * @param value 值
     * @return Boolean
     */
    public static Boolean lLeftPushList(String key, Object value, long time, TimeUnit timeUnit) {
        if (cn.hutool.core.util.ObjectUtil.isNull(value)) {
            return Boolean.FALSE;
        }
        try {
            log.debug("--------------------------------------------");
            stringRedisTemplate.opsForList().leftPush(key, objToStr(value));
            log.debug("Redis List left push  ==> key: {}, value: {}", key, value);
            log.debug("--------------------------------------------");

            if (time > 0) {
                expire(key, time, timeUnit);
            }
            return true;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return false;
        }
    }

    /**
     * 将list放入缓存
     *
     * @param key 键
     * @param value 值
     * @return Boolean
     */
    public static Boolean lBatchLeftPushList(String key, List<Object> value) {
        return lBatchLeftPushList(key, value, 0, TimeUnit.SECONDS);
    }

    /**
     * 将list放入缓存
     *
     * @param key   键
     * @param value 值
     * @param time  时间(秒)
     * @return Boolean
     */
    public static Boolean lBatchLeftPushList(String key, List<?> value, long time, TimeUnit timeUnit) {
        try {
            List<String> stringList = value.stream().filter(cn.hutool.core.util.ObjectUtil::isNotNull).map(RdsUtil::objToStr).collect(Collectors.toList());
            log.debug("--------------------------------------------");
            stringRedisTemplate.opsForList().leftPushAll(key, stringList);
            log.debug("Redis List batch left push  ==> key: {}, value: {}", key, value);
            log.debug("--------------------------------------------");
            if (time > 0) {
                expire(key, time, timeUnit);
            }
            return true;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return false;
        }
    }

    /**
     * 弹出list缓存的内容
     *
     * @param key 键
     * @return List<String>
     */
    public static String lRightPopList(String key) {
        try {
            return stringRedisTemplate.opsForList().rightPop(key);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return null;
        }
    }


    /**
     * 弹出list缓存的内容
     *
     * @param key 键
     * @param duration 持续时间
     * @return String
     */
    public static String lRightPopList(String key, Duration duration) {
        try {
            return stringRedisTemplate.opsForList().rightPop(key, duration);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return null;
        }
    }

    /**
     * 弹出list缓存的内容
     *
     * @param key 键
     * @return List<String>
     */
    public static String lLeftPopList(String key) {
        try {
            return stringRedisTemplate.opsForList().leftPop(key);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return null;
        }
    }

    /**
     * 弹出list缓存的内容
     *
     * @param key 键
     * @param duration 持续时间
     * @return String
     */
    public static String lLeftPopList(String key, Duration duration) {
        try {
            return stringRedisTemplate.opsForList().leftPop(key, duration);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return null;
        }
    }

    /**
     * 获取list缓存的内容
     *
     * @param key   键
     * @param start 开始
     * @param end   结束 0 到 -1 代表所有值
     * @return List<String>
     */
    public static List<String> lGetListRange(String key, long start, long end) {
        try {
            return stringRedisTemplate.opsForList().range(key, start, end);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return null;
        }
    }

    /**
     * 获取list缓存的长度
     *
     * @param key 键
     * @return Long
     */
    public static Long lGetListSize(String key) {
        try {
            return stringRedisTemplate.opsForList().size(key);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return 0L;
        }
    }

    /**
     * 通过索引 获取list中的值
     *
     * @param key   键
     * @param index 索引 index>=0时， 0 表头，1 第二个元素，依次类推；index<0时，-1，表尾，-2倒数第二个元素，依次类推
     * @return String
     */
    public static String lGetListByIndex(String key, long index) {
        try {
            return stringRedisTemplate.opsForList().index(key, index);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return null;
        }
    }

    /**
     * 根据索引修改list中的某条数据
     *
     * @param key   键
     * @param index 索引
     * @param value 值
     * @return /
     */
    public static Boolean lUpdateListValue(String key, long index, Object value) {
        try {
            stringRedisTemplate.opsForList().set(key, index, objToStr(value));
            return true;
        } catch (InvalidDataAccessApiUsageException e) {
            log.error("Redis update List index out of range", e);
            return false;
        }
    }

    /**
     * 移除N个值为value
     *
     * @param key   键
     * @param count 移除多少个
     * @param value 值
     * @return 移除的个数
     */
    public static Long lRemoveListValue(String key, long count, Object value) {
        try {
            return stringRedisTemplate.opsForList().remove(key, count, objToStr(value));
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return 0L;
        }
    }


    /*------------------zSet相关操作--------------------------------*/

    /**
     * 添加元素,有序集合是按照元素的score值由小到大排列
     *
     * @param key key
     * @param value value
     * @param score score
     * @return Boolean
     */
    public static Boolean zAdd(String key, Object value, double score) {
        if (ObjectUtil.isNull(value)) {
            return Boolean.FALSE;
        }
        return stringRedisTemplate.opsForZSet().add(key, objToStr(value), score);
    }

    /**
     * 是否zSet元素
     * @param key key
     * @param value value
     * @return Boolean
     */
    public static Boolean zIsMember(String key, Object value) {
        return Objects.nonNull(stringRedisTemplate.opsForZSet().score(key, objToStr(value)));
    }

    /**
     * 删除zSet
     * @param key key
     * @param value value
     * @return 被删除元素个数
     */
    public static Long zRemove(String key, Object value) {
        return zRemove(key, objToStr(value));
    }

    public static Long zRemove(String key, String value) {
        return stringRedisTemplate.opsForZSet().remove(key, value);
    }

    /**
     * 批量删除zSet
     * @param key key
     * @param values values
     * @return 被删除元素个数
     */
    public static Long zmRemove(String key, Object... values) {
        return stringRedisTemplate.opsForZSet().remove(key, values);
    }

    /**
     * 增加元素的score值，并返回增加后的值
     * @param key key
     * @param value value
     * @param delta delta
     * @return Double
     */
    public static Double zIncrementScore(String key, String value, double delta) {
        return stringRedisTemplate.opsForZSet().incrementScore(key, value, delta);
    }

    /**
     * 返回元素在集合的排名,有序集合是按照元素的score值由小到大排列
     *
     * @param key key
     * @param value value
     * @return 0表示第一位
     */
    public static Long zRank(String key, Object value) {
        return stringRedisTemplate.opsForZSet().rank(key, objToStr(value));
    }

    /**
     * 返回元素在集合的排名,按元素的score值由大到小排列
     *
     * @param key key
     * @param value value
     * @return 排名
     */
    public static Long zReverseRank(String key, Object value) {
        return stringRedisTemplate.opsForZSet().reverseRank(key, objToStr(value));
    }

    /**
     * 获取集合的元素, 从小到大排序
     *
     * @param key key
     * @param start 开始位置
     * @param end   结束位置, -1查询所有
     * @return Set<String>
     */
    public static Set<String> zRange(String key, long start, long end) {
        return stringRedisTemplate.opsForZSet().range(key, start, end);
    }

    /**
     * 获取集合的元素, 从大到小排序
     *
     * @param key key
     * @param start start
     * @param end end
     * @return Set<String>
     */
    public static Set<String> zReverseRange(String key, long start, long end) {
        return stringRedisTemplate.opsForZSet().reverseRange(key, start, end);
    }

    /**
     * 获取集合元素, 并且把score值也获取
     *
     * @param key key
     * @param start start
     * @param end end
     * @return Set<TypedTuple<String>>
     */
    public static Set<TypedTuple<String>> zRangeWithScores(String key, long start, long end) {
        return stringRedisTemplate.opsForZSet().rangeWithScores(key, start, end);
    }

    /**
     * 获取集合的元素, 从大到小排序, 并返回score值
     *
     * @param key key
     * @param start start
     * @param end end
     * @return Set<TypedTuple<String>>
     */
    public static Set<TypedTuple<String>> zReverseRangeWithScores(String key, long start, long end) {
        return stringRedisTemplate.opsForZSet().reverseRangeWithScores(key, start, end);
    }

    /**
     * 根据Score值查询集合元素
     *
     * @param key key
     * @param min 最小值
     * @param max 最大值
     * @return Set<String>
     */
    public static Set<String> zRangeByScore(String key, double min, double max) {
        return stringRedisTemplate.opsForZSet().rangeByScore(key, min, max);
    }

    /**
     * 根据Score值查询集合元素, 从小到大排序
     *
     * @param key key
     * @param min 最小值
     * @param max 最大值
     * @return Set<TypedTuple<String>>
     */
    public static Set<TypedTuple<String>> zRangeByScoreWithScores(String key, double min, double max) {
        return stringRedisTemplate.opsForZSet().rangeByScoreWithScores(key, min, max);
    }

    /**
     * 根据 Score 和 下标 获取集合元素
     * @param key key
     * @param min min
     * @param max max
     * @param start start
     * @param end end
     * @return Set<TypedTuple<String>>
     */
    public static Set<TypedTuple<String>> zRangeByScoreWithScores(String key, double min, double max, long start, long end) {
        return stringRedisTemplate.opsForZSet().rangeByScoreWithScores(key, min, max,
                start, end);
    }

    /**
     * 获取集合的元素, 从大到小排序, 并返回score值
     *
     * @param key key
     * @param pageSize pageSize
     * @return Set<TypedTuple<String>>
     */
    public static Set<TypedTuple<String>> zReverseRangeWithScores(String key, long pageSize) {
        return stringRedisTemplate.opsForZSet().reverseRangeByScoreWithScores(key, Double.MIN_VALUE,
                Double.MAX_VALUE, 0, pageSize);
    }

    /**
     * 获取集合的元素, 从大到小排序, 并返回score值
     *
     * @param key key
     * @param max max
     * @param pageSize pageSize
     * @return Set<TypedTuple<String>>
     */
    public static Set<TypedTuple<String>> zReverseRangeByScoreWithScores(String key, double max, long pageSize) {
        return stringRedisTemplate.opsForZSet().reverseRangeByScoreWithScores(key, Double.MIN_VALUE, max, 1, pageSize);
    }

    /**
     * 根据score值获取集合元素数量
     *
     * @param key key
     * @param min min
     * @param max max
     * @return Long
     */
    public static Long zCount(String key, double min, double max) {
        return stringRedisTemplate.opsForZSet().count(key, min, max);
    }

    /**
     * 获取集合大小
     *
     * @param key key
     * @return Long
     */
    public static Long zSize(String key) {
        return stringRedisTemplate.opsForZSet().size(key);
    }

    /**
     * 获取集合大小
     *
     * @param key key
     * @return Long
     */
    public static Long zCard(String key) {
        return stringRedisTemplate.opsForZSet().zCard(key);
    }

    /**
     * 获取集合中value元素的score值
     *
     * @param key key
     * @param value value
     * @return Double
     */
    public static Double zScore(String key, String value) {
        return stringRedisTemplate.opsForZSet().score(key, value);
    }

    /**
     * 移除指定索引位置的成员
     *
     * @param key key
     * @param start start
     * @param end end
     * @return Long
     */
    public static Long zRemoveRange(String key, long start, long end) {
        return stringRedisTemplate.opsForZSet().removeRange(key, start, end);
    }

    /**
     * 根据指定的score值的范围来移除成员
     *
     * @param key key
     * @param min min
     * @param max max
     * @return Long
     */
    public static Long zRemoveRangeByScore(String key, double min, double max) {
        return stringRedisTemplate.opsForZSet().removeRangeByScore(key, min, max);
    }

    /**
     * 获取key和otherKey的并集并存储在destKey中
     *
     * @param key key
     * @param otherKey otherKey
     * @param destKey destKey
     * @return 并集
     */
    public static Long zUnionAndStore(String key, String otherKey, String destKey) {
        return stringRedisTemplate.opsForZSet().unionAndStore(key, otherKey, destKey);
    }

    /**
     * 将指定Redis中key中元素和新集合元素放入
     * @param key key
     * @param otherKeys otherKeys
     * @param destKey destKey
     * @return Long
     */
    public static Long zUnionAndStore(String key, Collection<String> otherKeys, String destKey) {
        return stringRedisTemplate.opsForZSet().unionAndStore(key, otherKeys, destKey);
    }

    /**
     * 交集
     *
     * @param key key
     * @param otherKey otherKey
     * @param destKey destKey
     * @return Long
     */
    public static Long zIntersectAndStore(String key, String otherKey, String destKey) {
        return stringRedisTemplate.opsForZSet().intersectAndStore(key, otherKey, destKey);
    }

    /**
     * 交集
     *
     * @param key key
     * @param otherKeys 多个list的key
     * @param destKey 目标key
     * @return Long
     */
    public static Long zIntersectAndStore(String key, Collection<String> otherKeys, String destKey) {
        return stringRedisTemplate.opsForZSet().intersectAndStore(key, otherKeys, destKey);
    }

    /*------------------BigMap相关操作--------------------------------*/

    /**
     * Redis中是利用string类型数据结构实现BitMap，因此最大上限是512M，转换为bit则是 2^32个bit位。
     * 用于对 key 所储存的字符串值，设置或清除指定偏移量上的位(bit)。
     * 把每一个bit位对应当月的每一天，形成了映射关系。用0和1标示业务状态，这种思路就称为位图
     * （BitMap）。这样我们就用极小的空间，来实现了大量数据的表示
     * @param key key
     * @param offset 指定位置
     * @param value true设置 false清除
     * @return Boolean方法返回一个布尔值，表示设置之前该位的旧值。如果该位原来是 1，则返回 true；如果是 0，则返回 false。
     */
    public static Boolean sign(String key, Integer offset,Boolean value) {
        return stringRedisTemplate.opsForValue().setBit(key, offset, value);
    }

    /**
     * 获取当月连续签到次数
     * @param cacheKey key
     * @param localDateTime 本月天数
     * @return 次数
     */
    public static Long getContinuousSignCount(String cacheKey, Integer localDateTime) {
        List<Long> result = stringRedisTemplate.opsForValue().bitField(
                cacheKey,
                BitFieldSubCommands.create()
                        .get(BitFieldSubCommands.BitFieldType.unsigned(localDateTime)).valueAt(0)
        );
        if (result == null || result.isEmpty()) {
            // 没有任何签到结果
            return 0L;
        }
        Long num = result.get(0);
        if (num == null || num == 0) {
            return 0L;
        }
        // 6.循环遍历
        long count = 0;
        // 如果为0，说明未签到，结束
        // 如果不为0，说明已签到，计数器+1
        while ((num & 1) != 0) {
            // 6.1.让这个数字与1做与运算，得到数字的最后一个bit位 // 判断这个bit位是否为0
            count++;
            // 把数字右移一位，抛弃最后一个bit位，继续下一个bit位
            num >>>= 1;
        }
        return count;
    }

    /**
     * 获取用户签到次数
     */
    public static long getSignNum(String cacheKey) {
        Object execute = stringRedisTemplate.execute((RedisCallback) cbk -> cbk.bitCount(cacheKey.getBytes()));
        return Convert.convert(Long.class, execute, 0L);
    }

    /*---------------------------------------------------------------*/


    /*------------------HyperLogLog相关操作--------------------------------*/

    /**
     * 添加HyperLogLog数据
     * @param key key
     * @param values values
     * @return 添加数量
     */
    public static Long addHyperLogLog(String key, String... values) {
        try {
            return stringRedisTemplate.opsForHyperLogLog().add(key, values);
        }catch (Exception e) {
            System.out.println(e.getMessage());
            log.error(e.getMessage(), e);
        }
        return 0L;
    }

    /**
     * 获取HyperLogLog数量
     * @param key key（多个key可以通过通配符获取总数）
     * @return count
     */
    public static Long getHyperLogLogSize(String... key) {
        return stringRedisTemplate.opsForHyperLogLog().size(key);
    }

    /**
     * 删除HyperLogLog数据
     * @param key key
     */
    public static void delHyperLogLog(String key) {
        stringRedisTemplate.opsForHyperLogLog().delete(key);
    }

    /*---------------------------------------------------------------*/

    /*------------------GEO相关操作--------------------------------*/
    /**
     * 添加GEO数据
     * @param key key
     * @param point point
     * @param member member
     * @return Long
     */
    public static Long addGeo(String key, Point point, String member) {
        return stringRedisTemplate.opsForGeo().add(key, point, member);
    }

    /**
     * 返回两个点位之间的距离
     * @param key key
     * @param member1 member1
     * @param member2 member2
     * @return Distance
     */
    public static Distance distance(String key, String member1, String member2) {
        return stringRedisTemplate.opsForGeo().distance(key, member1, member2);
    }

    /**
     * 返回一个或多个位置元素的 GeoHash 表示
     * @param key key
     * @param members members
     * @return List<String>
     */
    public static List<String> getGeoHash(String key, String... members) {
        return stringRedisTemplate.opsForGeo().hash(key, members);
    }

    /**
     * 获取一个或多个点位
     * @param key key
     * @param members members
     * @return List<Point>
     */
    public static List<Point> position(String key, String... members) {
        return stringRedisTemplate.opsForGeo().position(key,members);
    }

    /**
     * 以给定的经纬度为中心， 找出某一半径内的元素
     * @param key key
     * @param member 圆点
     * @param distance 半径
     * @return GeoResults<RedisGeoCommands.GeoLocation<String>>
     */
    public static GeoResults<RedisGeoCommands.GeoLocation<String>> radius(String key, String member, Distance distance) {
        return stringRedisTemplate.opsForGeo().radius(key, member, distance);
    }
    /*---------------------------------------------------------------*/

    /*------------------publish相关操作--------------------------------*/

    /**
     * 发布消息
     * @param topic 发布主题
     * @param message 消息
     */
    public static void publishMessage(String topic, String message) {
        stringRedisTemplate.convertAndSend(topic, message);
    }

    /*---------------------------------------------------------------*/

    /*------------------stream相关操作--------------------------------*/

    /**
     * 获取opsForStream
     * @return StreamOperations<String, Object, Object>
     */
    public static StreamOperations<String, Object, Object> getOpsForStream() {
        return stringRedisTemplate.opsForStream();
    }

    /*---------------------------------------------------------------*/

    public static RBloomFilter<Object> getBloomFilter(String filterName, Long expectedInsertions, Double falseProbability) {
        RBloomFilter<Object> bloomFilter = redissonClient.getBloomFilter(filterName);
        bloomFilter.tryInit(expectedInsertions, falseProbability);
        return bloomFilter;
    }

    /**
     * 开始时间戳
     */
    private static final long BEGIN_TIMESTAMP = 1640995200L;
    /**
     * 序列号的位数
     */
    private static final int COUNT_BITS = 32;
    /**
     * 生成唯一id
     * @return 唯一id
     */
    public static long nextId(String keyPrefix) {

        // 1.生成时间戳
        LocalDateTime now = LocalDateTime.now();
        long nowSecond = now.toEpochSecond(ZoneOffset.UTC);
        long timestamp = nowSecond - BEGIN_TIMESTAMP;
        // 2.生成序列号
        // 2.1.获取当前日期，精确到天
        String date = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        // 2.2.自增长
        long count = stringRedisTemplate.opsForValue().increment("icr:" + keyPrefix + ":" + date);
        // 3.拼接并返回
        return timestamp << COUNT_BITS | count;

    }

    /**
     * 分布式锁
     * @param key key
     * @param value 值
     * @param time 时间
     * @param timeUnit 时间单位
     * @return 加锁结果
     */
    public static Boolean lock(String key, String value, long time, TimeUnit timeUnit) {
        return stringRedisTemplate.opsForValue().setIfAbsent(key, value, time, timeUnit);
    }

    /**
     * 解锁
     * @param key key
     */
    public static void unlock(String key) {
        stringRedisTemplate.delete(key);
    }

    /**
     * 添加延时消息
     * @param message 消息
     * @param delaySeconds 延时秒数
     */
    public static void addDelayMessage(Integer type, String message, long delaySeconds) {
        DelayMessage delayMessage = new DelayMessage();
        delayMessage.setId(IdUtil.getSnowflakeNextIdStr());
        delayMessage.setType(type);
        delayMessage.setContent(message);
        delayMessage.setExpireTime(System.currentTimeMillis() + delaySeconds * 1000);
        // 将消息放到ZSet
        stringRedisTemplate.opsForZSet().add(RedisKeyConstant.DELAY_QUEUE_KEY, JSON.toJSONString(delayMessage), delayMessage.getExpireTime());
    }

    /**
     * 脚本执行
     * @param script 脚本
     * @param clazz 返回值类型
     * @param keys  key
     * @param args 参数
     * @return <T>
     */
    public static <T> T script(String script, Class<T> clazz, List<String> keys, Object... args) {
        RedisScript<T> redisScript = RedisScript.of(script, clazz);
        return stringRedisTemplate.execute(redisScript, keys, args);
    }

}
